import { useState, useEffect } from 'react';
import { useAuthStore } from '@/store/auth';
import { useChain } from '@/context/ChainContext';
import { multiChainApi } from '@/lib/multi-chain-api';
import { API_ENDPOINTS } from '@/config/api';

interface VestingStatus {
  isVestingBeneficiary: boolean;
  vestingData: any | null;
  isLoading: boolean;
  error: string | null;
}

export function useVestingCheck() {
  const { getAdminForChain } = useAuthStore();
  const { currentChain } = useChain();
  
  const admin = getAdminForChain(currentChain);
  const [vestingStatus, setVestingStatus] = useState<VestingStatus>({
    isVestingBeneficiary: false,
    vestingData: null,
    isLoading: false,
    error: null,
  });

  useEffect(() => {
    async function checkVestingStatus() {
      if (!admin?.wallet_address) {
        setVestingStatus({
          isVestingBeneficiary: false,
          vestingData: null,
          isLoading: false,
          error: null,
        });
        return;
      }

      setVestingStatus(prev => ({ ...prev, isLoading: true, error: null }));

      try {
        // Check vesting status using the upgradeable contracts API
        const response = await multiChainApi.getClient(currentChain).get(
          API_ENDPOINTS.contracts.vesting.beneficiary(admin.wallet_address)
        );

        const vestingData = response.data;
        const hasVesting = vestingData.summary?.schedule_count > 0;

        setVestingStatus({
          isVestingBeneficiary: hasVesting,
          vestingData: hasVesting ? vestingData : null,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        // If the API call fails, it might mean no vesting schedules exist
        const isNotFoundError = error.response?.status === 404;
        
        setVestingStatus({
          isVestingBeneficiary: false,
          vestingData: null,
          isLoading: false,
          error: isNotFoundError ? null : error.message || 'Failed to check vesting status',
        });
      }
    }

    checkVestingStatus();
  }, [admin?.wallet_address]);

  return vestingStatus;
}